package com.apobates.forum.core.impl.dao;

import com.apobates.forum.core.dao.AlbumPictureDao;
import com.apobates.forum.core.entity.AlbumPicture;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author xiaofanku
 * @since 20200512
 */
@Repository
public class AlbumPictureDaoImpl implements AlbumPictureDao{
    @PersistenceContext
    private EntityManager entityManager;
    private final static Logger logger = LoggerFactory.getLogger(AlbumPictureDaoImpl.class);
    
    @Override
    public Stream<AlbumPicture> findAllByAlbum(long albumId) {
        return entityManager.createQuery("SELECT ap FROM AlbumPicture ap WHERE ap.status = ?1 AND ap.album.id = ?2", AlbumPicture.class).setParameter(1, true).setParameter(2, albumId).getResultStream();
    }
    
    @Override
    public Stream<AlbumPicture> findAllByAlbum(Collection<Long> albumIdSet) {
        if (albumIdSet == null || albumIdSet.isEmpty()) {
            return Stream.empty();
        }
        return entityManager.createQuery("SELECT ap FROM AlbumPicture ap WHERE ap.status = ?1 AND ap.album.id IN ?2", AlbumPicture.class).setParameter(1, true).setParameter(2, albumIdSet).getResultStream();
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Optional<Integer> delete(Collection<Long> idSet) {
        if (idSet == null || idSet.isEmpty()) {
            return Optional.empty();
        }
        int affect = entityManager.createQuery("UPDATE AlbumPicture ap SET ap.status = ?1 WHERE ap.id IN ?2").setParameter(1, false).setParameter(2, idSet).executeUpdate();
        return Optional.of(affect);
    }
    
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void save(AlbumPicture entity) {
        entityManager.persist(entity);
    }
    
    @Override
    public Optional<AlbumPicture> findOne(Long primaryKey) {
        return Optional.ofNullable(entityManager.find(AlbumPicture.class, primaryKey));
    }
    
    @Override
    public Optional<Boolean> edit(AlbumPicture updateEntity) {
        return Optional.empty();
    }
    
    @Override
    public Stream<AlbumPicture> findAll() {
        return Stream.empty();
    }
    
    @Override
    public Long count() {
        return -1L;
    }
}